<template>
  <div class="tr-select-tree-box">
    <el-select
      v-model="selectVal"
      :disabled="disabled"
      clearable
      ref="select"
      @clear="clearHandle"
    >
      <el-input
        class="input"
        placeholder="请输入查询关键字"
        prefix-icon="el-icon-search"
        v-model="treeFilter"
        clearable
      ></el-input>
      <el-option hidden key="id" :value="selectVal" :label="selectName">
      </el-option>
      <el-tree
        class="tree-select"
        :data="treeData"
        :props="defaultProps"
        @node-click="handleNodeClick"
        :expand-on-click-node="false"
        :check-on-click-node="true"
        ref="tree"
        node-key="id"
        :default-expand-all="true"
        :filter-node-method="filterNode"
      >
        <span slot-scope="{ data }">
          <span>{{ data[showWord] }}</span>
        </span>
      </el-tree>
    </el-select>
  </div>
</template>

<script>
import { findByProperty } from "@/utils/util";
export default {
  name: "TrSelectTree",
  props: {
    value: {
      type: String,
      default: "",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    treeData: {
      type: Array,
      default: () => [],
    },
    showWord: {
      type: String,
      default: "label",
    },
    valueWord: {
      type: String,
      default: "value",
    },
    defaultKeys: {
      type: Array,
      default: () => [],
    },
    ftObj: {
      type: Object,
      default: () => {},
    },
    defaultProps: {
      type: Object,
      default: () => ({
        children: "children",
        label: "label",
      }),
    },
  },
  data: () => ({
    selectVal: "",
    selectName: "",
    treeFilter: "",
  }),
  watch: {
    selectVal(newValue) {
      this.$emit("input", newValue);
    },
    treeFilter(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    clearHandle() {
      this.selectVal = "";
      this.selectName = "";
    },
    handleNodeClick(data) {
      this.selectVal = data[this.valueWord];
      this.selectName = data[this.showWord];
      this.treeFilter = "";
      this.$refs.select.blur();
      this.$emit("selectBack", this.ftObj);
    },
    filterNode(value, data) {
      if (!value) return true;
      let filterRes = data[this.showWord].indexOf(value) !== -1;
      return filterRes;
    },
  },

  mounted() {
    this.selectVal = this.value;
    if (this.selectVal) {
      let fItem = findByProperty(this.treeData, this.valueWord, this.value);
      if (fItem) this.selectName = fItem[this.showWord];
    }
  },
};
</script>
